//<script type='text/javascript'>


/////// LIST CLASS
var List = function (vars) {
	Object.extend(obj = new Element("div", {id:vars.id, class:"list"}), win.asset.list);
	Object.extend(obj.vars = vars, vars.meta);
	obj.vars.addtool = vars.tool; /// MEH...
	
	if(vars['new']) obj.blank(vars['new']);
	if(vars.descr) obj.appendChild(new Element("div", {class:"descr"})).update(vars.descr);
	obj.appendChild(tbl = new Element("table", {id:obj.id+".table", class:"list border", cellspacing:0, cellpadding:0 }));
	tbl.appendChild(t = new Element("tbody", {id:obj.id+".tbody"}));
	
	obj.observe("mouseover", controls.bubble );
	if(vars.floats) obj.seed(vars.floats, vars.flow, t);
	return obj;
}

win.asset.list	= {
	objtype	: "list",
	seed	: function(floats, flow, trg) {
		if(!trg) trg = $(this.id + ".tbody");
		if(flow) this.vars.flow = flow;
		trg.update();
		
		this.vars.floatlist = [];
		if(!this.vars.grid) this.vars.grid = floats[0].length;
       	if(floats[0][0]) {
            floats.each(function(line, n){
                tr = new Element("tr",{class:(n%2)?"odd":""});
                if(!line.length) tr.appendChild(new Element('td',{colspan:this.vars.grid}));
                line.each(function(cell) { tr.appendChild(new Element('td').update((cell!="") ?cell:'&nbsp;')); });
                trg.appendChild(tr);
                this.vars.floatlist.push(n);
           	}, this);
        } else { n = 0;
            floats.each(function(line, n){
            	line.class = (n%2)?"odd":"";
            	tr = new win.trfloat(line);
				trg.appendChild( tr );
                this.vars.floatlist.push(line.id);
            n++; }, this);
        }
		this.setStyle({opacity: 1, minHeight: "auto"});
		if(this.vars.flow) controls.position(this);
    },
    request	: function(flow) {
    	if(flow) this.vars.flow = flow;
    	this.setStyle({opacity: 0.5, minHeight: this.getHeight()});
       	xhttp.send('control.call.php', {trg:this.id, wtype:"push", tool:this.vars.tool, action:"list", vars:this.vars});
    }
}
Object.extend(win.asset.list, win.asset._proto_);



/////// DROPBOX CLASS
var Dropbox = function (vars) {
	
	// Create element
	Object.extend( obj = engine.generate_unique_element( "dropbox" ) , win.asset.dropboxMK2);
	obj.vars = vars;
	
	
	// Add button required?
	if( vars.blank ) obj.blank( vars.blank );
	else if( vars.new_media ) obj.new_media( vars.new_media );
	
	// Add child elements
	obj.appendChild( new Element( "span", { "class": "name" } )).update( vars.descr );
	obj.insert( obj.box = new Element( "ul", { "id": obj.id + ".box", "class": "box" } ));
	obj.appendChild( new Element( "span", { "class": "comment" } ));
	
	//obj.observe("mouseover", controls.bubble );

	return ( vars.floats )? obj.seed( vars.floats ) : obj;
}

win.asset.dropboxMK2	= {
	all			: {},
	seed		: function(floats, flow ) {
        
        box = this.box;
        
		floats.each( function(el) { box.insert( new Li( el )); });
		
		this.box.floats = floats;
		this.sortable( box );
		
		return this;
		
    },
    check		: function(e){
        
		dropbox = e.up(0);
		
        am_stored  = dropbox.box.floats.length;
        am_current = dropbox.box.childElements().length;
        
		///// PARSE NEW ORDER
		new_floats = [];
		dropbox.box.childElements().each( function( child ){
			new_floats.push( child.vars );
		});
		
		Object.extend( params = { floats: new_floats  }, dropbox.vars );

        
    	///// CALCULATE CHANGES
		if		( am_current > am_stored ) params.add		= new_floats.findAll( function( value ) { return !dropbox.box.floats.include( value ); });
		else if	( am_current < am_stored ) params.remove	= dropbox.box.floats.findAll( function( value ) { return !new_floats.include( value ); });
		

		dropbox.box.floats = new_floats;
		dashboard.user.logtime( init.session );

		
		return dropbox.request( "sortable", params );
        
        /* to do (make pages work):
        
        // RECALC MINISUB
        if(vars.miniview) $(vars.miniview).setStyle({background:"url("+engine.path.img+"float.line.subdrop."+((newn>9)?"n":newn)+".png)"});
        
		*/
    },
    
    unset		: function() {
		delete win.asset.dropboxMK2.all[ this.id + ".box" ];
		this.sortable( false );
    },
    
    add			: function(e) {
        vars = win.asset.dropbox.list[this.parentNode.id];
        xhttp.send('control.call.php', {trg:this.parentNode.id, wtype:'push', tool:vars.tool, action:'add', 'vars':vars});
    },
    new_media	: function(vars) {
    	el = this.blank();
    	el.update( new Element("span", {id:el.id+".trg"}).update('...connecting') );
    	
    	Object.extend(loadcluster.init, {
			button_placeholder_id: el.id+".trg",
			post_params : { account :'<?=ACCOUNT?>', auth:<?=$_user['ID']?>, objtype : vars.type, active : 0 },
			custom_settings : { float_target : this.id, objtype : vars.type }
		} );
		
		setTimeout( function() { var swfu = new SWFUpload( loadcluster.init ); }, 200 );
	},
	
	sortable	: function( ul ) {
		
		related = [];
		$$( "ul.box" ).each( function( box ) {
			if( box.up(0).vars.type == ul.up(0).vars.type ) related.push( box.id );
		}).each( function( box ) {
			Sortable.create( box.id , { dropOnEmpty:true, ghosting:false, constraint:false, containment: related, onUpdate: box.up(0).check });
		});
    },
    
    request	: function( action, param ) {
		Object.extend( param, {trg: this.id, transfer_type: "push", action: action } );
		xhttp.send( 'control.call.php', param );

		return this;
	}
}
Object.extend(win.asset.dropboxMK2, win.asset._proto_);


/////// OPTIONS CLASS
var Options = function (vars) {
	Object.extend(obj = new Element("div", {id:vars.id, class:"options"}), win.asset.options);
	obj.vars = vars.meta;
	obj.vars.addtool = vars.tool; /// MEH...
	if(vars.active) obj.toggleClassName("active");
	
	obj.appendChild(new Element("div", {id:vars.id+".comment", class: "comment"}));
	obj.appendChild(name = new Element("div", {id:vars.id+".name", class: "name"})).update(vars.descr||"...");
	obj.appendChild(ul = new Element("ul", {id:obj.id+".ul", class:vars.class || ""}));
	
	name.observe('mouseover', function(){ this.toggleClassName("active"); });
	name.observe('mouseout', function(){ this.toggleClassName("active"); });
	name.observe('click', function(){ this.parentNode.toggleClassName("active"); });
	if(vars.floats) obj.seed(vars.floats, ul);
	
	return obj;
}

win.asset.options	= {
	seed	: function(floats, trg) {
		if(!trg) trg = $(this.id + ".ul");
		trg.update();
		this.vars.floatlist = [];
		
       	floats.each(function(child){
            trg.appendChild( new Element("li").update(child) );
            this.vars.floatlist.push(child.id);
        }, this);
       
        
    }
}
Object.extend(win.asset.options, win.asset._proto_);




//FEED OBJECT
win.asset.feed	= {
    list	: {},
    build	: function(vars) {
        
        if(!vars.grid) vars.grid = vars.values[0].length;
        if(vars.descr) $(vars.id).insert({before:new Element("font", {class:'fielddescr'}).update(vars.descr)});
        if(vars['new']) {
            $(vars.id).previousSibling.setStyle({float:"left"});
            $(vars.id).insert({before: new Element("div", {id:vars.id+".new", class:"ico new", style:"float:right;"}).observe("click",win.asset.list.add)});
            $(vars.id+".new").appendChild(new Element("span", {id:vars.id+".new.txt"}).update(vars['new']));
        }
        
        t = new Element("tbody", {id:vars.id+".tbody"});
        $(vars.id).appendChild(t);
        vars.floats = win.asset.list.seed(vars.id, vars.values, vars.type, vars.grid);
        
        
        $(vars.id).addClassName("list");
        win.asset.list.list[vars.id] = vars;
    },
    seed	: function(id, floats, type, grid) {
        floatidset = [];
        if(floats[0][0]) {
            floats.each(function(line, n){
                tr = new Element("tr",{class:(n%2)?"odd":""});
                if(!line.length) tr.appendChild(new Element('td',{colspan:grid}));
                line.each(function(cell) { tr.appendChild(new Element('td').update((cell!="") ?cell:'&nbsp;')); });
                $(id+".tbody").appendChild(tr);
                floatidset.push(n);
            });
        } else if(floats) { n = 0;
            floats.each(function(line){
				$(id+".tbody").appendChild(win.asset.list.el(line, type));
                floatidset.push(line.id);
            n++; });
        }
        
        return floatidset;
    },
	el		: function(line, type) {
		tr = new Element("tr",{id:"float_"+type+"."+line.id, class:(n%2)?"odd":""}).observe("click",function(){ win.asset.list.plus(this); });
		tr.observe("mouseover", function(){ win.asset.objlist.setlinefloat(this); });
		line.list.each(function(cell) { tr.appendChild(new Element('td').update((cell!="") ?((typeof cell == "object")?line[cell.ref]:cell):'&nbsp;')); });
		return tr;
	},
    plus	: function(tr) {
        obj = this.list[tr.ancestors()[2].id];
        obj.vars.id = tr.id.split("."); obj.vars.id= obj.vars.id[1];
        $('column_right').insert(win.asset.el('asset.obj.'+obj.vars.type+'.'+obj.id, obj.tool, 'edit', obj.vars), {position:'after'});
    },
    add		: function(e) {
        vars = win.asset.list.list[this.nextSibling.id];
		xhttp.send('control.call.php', {trg:this.nextSibling.id, wtype:'push', tool:vars.tool, action:'add', 'vars':vars});
    },
    kill	: function(tr) {
		delete this.list[tr.ancestors()[2].id];
		vars = win.float.list[tr.id];
		xhttp.send('control.call.php', {trg:tr.ancestors()[2].id+".comment", wtype:'push', tool:vars.tool, action:"kill", 'vars':vars});
		tr.remove();
    },
}


// DROPBOX OBJECT
win.asset.dropbox	= {
    list		: {},
    typeref		: {},
    sortable	: function(type) {
        win.asset.dropbox.typeref[type].each( function(boxid){
            if($(boxid)) Sortable.create(boxid, {tag:'div', dropOnEmpty:true, constraint:false, containment:win.asset.dropbox.typeref[type], onUpdate:win.asset.dropbox.check });
        });
    },
    crop	: function(parent,wam,h) {
        parent.setStyle({height:(Math.ceil(parent.childElements().length/wam)*((h)?h:64))+"px"});
    },
    check	: function(e){
        vars = win.asset.dropbox.list[e.parentNode.id];
        
        //aaaaaaaaaaaarrrrrrrrrgggggggggghhhhhhhhh!!
        if(!vars.floats) vars.floats = vars.meta.floats;
        // end argh
        oldn = vars.floats.size();
        newn = e.childElements().length;
        
        ///// PARSE NEW ORDER
        newfloats = [];
        e.childElements().each(function(child){
            newfloats.push(win.float.list[child.id].id);
        });
        
        // SET NEW ORDER
        if(newn > oldn) vars.addchild	= newfloats.findAll(function(v) { return !vars.floats.include(v); }); else delete vars.addparent;  
        if(newn < oldn) vars.killchild	= vars.floats.findAll(function(v) { return !newfloats.include(v); }); else delete vars.killparent;
        vars.floats = newfloats;
        xhttp.send('control.call.php', {trg:vars.id+".comment", wtype:'push', tool:vars.tool, action:"hierarchy", 'vars':vars});
        delete vars.addchild; delete vars.killchild;	
        // RECALC MINISUB
        if(vars.miniview) $(vars.miniview).setStyle({background:"url("+engine.path.img+"float.line.subdrop."+((newn>9)?"n":newn)+".png)"});
        
        win.asset.dropbox.list[vars.id] = vars;
        dashboard.user.logtime(init.session);
    },
    flow	: function(n,btn) {
        id = btn.parentNode.parentNode.id;
        vars = win.asset.dropbox.list[id];
        $(id+".box").setStyle({height:$(id+".box").getHeight()+"px"}); 
        $(id+".box").update("loading...");
        
        vars.flow.cur = win.asset.dropbox.list[id].flow.cur = (vars.flow.cur+n <=0)? Math.ceil(vars.flow.total/vars.flow.itv)-1 : ((vars.flow.cur+n>=Math.ceil(vars.flow.total/vars.flow.itv))?0:vars.flow.cur+n);
        xhttp.send('control.call.php', {trg:btn.parentNode.id+".comment", wtype:'push', tool:vars.tool, action:'list.update', 'vars':vars});
        win.float.list = $H(win.float.list);
        $(id+".box").childElements().each( function(e){ win.float.list.unset(e.id); });
    },
    refill	: function(id,floats) {
        vars = win.asset.dropbox.list[id];
        $(id+".box").update();
        vars.floats = win.asset.dropbox.seed(id+'.box', floats, vars.type);
        win.asset.dropbox.list[id] = vars;
    },
    build	: function(vars) {
        $(vars.id).className = "dropbox";
        if(vars.class) $(vars.id).addClassName(vars.class);
        if(vars['new']) {
            $(vars.id).appendChild(new Element("div", {id:vars.id+".new", class:"ico new", style:"float:right;"}).observe("click",win.asset.dropbox.add));
            $(vars.id+".new").appendChild(new Element("span", {id:vars.id+".new.txt"}).update(vars['new']));
        }
        $(vars.id).appendChild(new Element("div", {'class':"name"})).update(vars.descr);
        $(vars.id).appendChild(new Element("div", {id:vars.id+'.box', 'class':"box"}));
        if(vars.flow) {
            $(vars.id).appendChild(new Element("div", {id:vars.id+".flow", class:"flow"}));
            $(vars.id+".flow").appendChild(new Element("input", {id:vars.id+".flow.next", type:'button', class:'ico next', style:'float:right'}).observe('click',function(){win.asset.dropbox.flow(1,this)}));
            $(vars.id+".flow").appendChild(new Element("input", {id:vars.id+'.flow.prev', type:'button', class:'ico prev'}).observe('click',function(){win.asset.dropbox.flow(-1,this)}));
            $(vars.id+".flow").appendChild(new Element("font", {id:vars.id+'.flow.comment', style:'position:relative; left:12px; top:-5px;'}).update("toont "+(vars.flow.cur*vars.flow.itv+1)+" - "+((vars.flow.cur+1)*vars.flow.itv)+" van "+vars.flow.total));
        }
        $(vars.id).appendChild(new Element("div", {'id':vars.id+".comment",'class':"comment"}));
        
        vars.floats = win.asset.dropbox.seed(vars.id+'.box', vars.floats, vars.type);
        win.asset.dropbox.list[vars.id] = vars;
        
		//$(vars.id).observe('mouseover', function(){ this.listfloat(); });
        
        
        /// TEMP ADDITION
      //  $(vars.id).observe("mouseover", controls.bubble );
      //  $(vars.id).objtype = "list.temp";

    },
    
    seed	: function(id, floats, type) {
        floatidset = [];
        if(floats) {
            $(id).setStyle({height:"auto"});
            floats.each(function(float){
                $(id).appendChild( win.float.el(float) );
                floatidset.push(float.id);
            });
        }
        if(!win.asset.dropbox.typeref[type]) win.asset.dropbox.typeref[type] = [id];
        else win.asset.dropbox.typeref[type].unshift($(id).id);
        win.asset.dropbox.sortable(type);
        
        return floatidset;
    },
    
    unset	: function(type, id) {
        delete win.asset.dropbox.typeref[type][id];
        delete win.asset.dropbox.list[id]
        
        win.asset.dropbox.typeref[type].each( function(boxid){
            Sortable.create(boxid, {tag:'div', dropOnEmpty:true, containment:win.asset.dropbox.typeref[type], onUpdate:win.asset.dropbox.check });
        });
    },
    
    add		: function(e) {
       // vars = win.asset.dropbox.list[this.parentNode.id];
       // xhttp.send('control.call.php', {trg:this.parentNode.id, wtype:'push', tool:vars.tool, action:'add', 'vars':vars});
        vars = win.asset.dropbox.list[this.parentNode.id];
    	$('column_right').insert( new Win('asset.obj.'+vars.type+'.'+dashboard.date.getTime()).request({tool:vars.tool, action:'edit.new', "vars":vars}) );
    }
}


// OBJECT LIST (hybrid dropbox/list field)
// OBJECT SKELETON (vars): { id:int|str, type:int, tool:dotted str, action:string, [name:string], [descr:string], [list:array], [meta:{ [floats:array], ... }]}
win.asset.objlist	= {
    list	: {},
    current : false,
    
    build	: function(obj) {
        $(obj.trg).className = "objlist";
        if(obj.vars['new']) {
            $(obj.trg).appendChild(new Element("div", {id:obj.trg+".new", class:"ico new", style:"float:right;"}).observe("click",win.asset.objlist.add));
            $(obj.trg+".new").appendChild(new Element("span", {id:obj.trg+".new.txt"}).update(obj.vars['new']));
        }
        $(obj.trg).appendChild(new Element("div", {'class':"name"})).update(obj.vars.boxdescr);
        $(obj.trg).appendChild(new Element("div", {id:obj.trg+'.box', class:"box" }));
        $(obj.trg).appendChild(new Element("table", {id:obj.trg+'.list', class:"list border", cellpadding:0, cellspacing:0 }));
        $(obj.trg+".list").appendChild(new Element("tbody", {id:obj.trg+".tbody"}));
        $(obj.trg).appendChild(new Element("div", {'id':obj.trg+".comment",'class':"comment"}));
        
        $(obj.trg+((obj.vars.viewtype=="box")?".list":".box")).setStyle({display:"none"});
        
        win.asset.list.seed(obj.trg, obj.floats, obj.vars.type, obj.vars.grid);
        obj.floats = win.asset.dropbox.seed(obj.trg+'.box', obj.floats, obj.vars.type);
        win.asset.dropbox.list[obj.trg] = obj;
        win.asset.list.list[obj.trg] = obj;
        win.asset.objlist.list[obj.trg] = obj;
        
        //if(!$('listfloat')) win.asset.objlist.init();
        
        $(obj.trg).observe('mouseover',function(){ if(!$("listfloat").visible() || win.asset.objlist.current != this.id) win.asset.objlist.setfloat(this.id); });
        
        if(obj.views) {
            obj.views.unshift(0);
            obj.views.unshift({id:obj.trg+'.btn.swapview', type:'button', descr:((obj.vars.viewtype=="list")?"floats":"list")+" view", func:win.asset.objlist.doswitch });
        }
    
    },
    doswitch: function() {
            $(win.asset.objlist.current+".list").toggle();
            $(win.asset.objlist.current+".box").toggle();
            
            
            
            win.asset.objlist.list[win.asset.objlist.current].init = view = $(win.asset.objlist.current+".box").visible()? "box":"list";
            win.asset.objlist.list[win.asset.objlist.current].views[0].descr = (view == "box")? "list view":"floats view";
            win.asset.objlist.setfloat(win.asset.objlist.current);
        
    },
    setfloat	: function(id) {
        
        obj = win.asset.objlist.list[id];
        $("listfloat").clonePosition(id, {setWidth:false, setHeight:false, offsetLeft:0, offsetTop:$(id).getHeight()-6});
        $("listfloat").className = "listfloat set"+obj.vars.viewtype;
        //$("listfloat.descr").update(vars.descr);
        
        $("listfloat.display").update();
        $("listfloat").show();
        if(obj.views) {
            win.asset.buttonline.build({id:"listfloat.display", assetref:id, cont:obj.views});
        }

        win.asset.objlist.current = id;
        
        
    },
    setlinefloat	: function(tr) {
    
		if(win.asset.objlist.currentline != tr) {
			obj = win.float.list[tr.id];
			$("linefloat").clonePosition(tr, {setWidth:false, setHeight:true, offsetLeft:tr.getWidth()-52, offsetTop:0});
			win.asset.objlist.currentline = tr;
			$("linefloat").show();
		}
        
        
    },
    blurfloat	: function() {
        id		= win.asset.objlist.current;
        vars	= win.asset.objlist.list[id];
        win.contr.listfloat.current = 0;
        
		$("listfloat").hide();
		$("linefloat").hide();
    },
    add 	: function(e) {
        vars = win.asset.objlist.list[this.parentNode.id].vars;
		$('column_right').insert(win.asset.el('asset.obj.'+vars.type+'.'+dashboard.date.getTime(), vars.tool, 'edit.new', vars), {position:'after'});
        //xhttp.send('control.call.php', {trg:this.parentNode.id, wtype:'push', tool:vars.tool, action:'add', 'vars':vars});
    }	,
    refresh	: function(trg, floats, type) {
		$(trg+".tbody").update();
        win.asset.list.seed(trg, floats, type);
        //vars.floats = win.asset.dropbox.seed(vars.id+'.box', vars.floats, vars.type);
		//asset.object.1.list.cont.objlist
		//asset.object.1.list.cont.objlist.tbody
    }
}


// TO WORK OUT!!!!!
/* sexy code examples:
			this.eventList = this.eventList || {};
			this.eventList[evType] = this.eventList[evType] || [];
			this.eventList[evType].push(evFunc);
			
			/////
			
			var args = bkLib.toArray(arguments), evType = args.shift();
			if(this.eventList && this.eventList[evType]) {
			for(var i=0;i<this.eventList[evType].length;i++) {
				this.eventList[evType][i].apply(this,args);
			}
		}

*/
